﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.PrintService;
using CoreShop.Services;
using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using CoreShop.Model.FromBody;
using CoreShop.Services.Services.System;
using CoreShop.Model.UI;
using gregn6Lib;
using CoreShop.App.Units.Interface;
using System.Threading.Tasks;
using Loading;
using Axgregn6Lib;

namespace CoreShop.App
{
    public partial class frmClassOff : UIForm
    {
        private Axgregn6Lib.AxGRPrintViewer axGRPrintViewer1 = new Axgregn6Lib.AxGRPrintViewer();
        private GridppReport Report = new GridppReport();
        protected GridppReport SubFoodType = new GridppReport();//商品分类
        protected GridppReport SubFoodDepart = new GridppReport();//商品部门
        ClassDataDto classData = new ClassDataDto();
        OpaqueCommand cmd = new OpaqueCommand();
        public frmClassOff()
        {
            InitializeComponent();
            //this.Height = Program.frmMainWin.Height - 50;
            try
            {
                this.axGRPrintViewer1 = new Axgregn6Lib.AxGRPrintViewer();
                ((System.ComponentModel.ISupportInitialize)(this.axGRPrintViewer1)).BeginInit();
                this.axGRPrintViewer1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.axGRPrintViewer1.Enabled = true;
                this.axGRPrintViewer1.Location = new System.Drawing.Point(0, 0);
                this.axGRPrintViewer1.Name = "axGRPrintViewer1";
                this.axGRPrintViewer1.Size = new System.Drawing.Size(712, 470);
                this.axGRPrintViewer1.TabIndex = 1;
                this.pnlGridReport.Controls.Add(this.axGRPrintViewer1);
                ((System.ComponentModel.ISupportInitialize)(this.axGRPrintViewer1)).EndInit();

                var schemedetailList = new corecmsprintschemedetailServices().SelectByBilltypeId((int)GlobalEnumVars.PrintbillType.ClassBill);
                if (schemedetailList != null) 
                {
                    var schemedetail = schemedetailList.FirstOrDefault();
                    var billtemplate = schemedetail.billtemplate;
                    if (billtemplate == null) return;
                    if (billtemplate.reportData.IsNullOrEmpty())
                    {
                        string sFile = System.Windows.Forms.Application.StartupPath + "\\report\\" + billtemplate.reportFile;
                        Report.LoadFromFile(sFile);
                    }
                    else
                    {
                        Report.LoadFromStr(billtemplate.reportData);
                    }
                    axGRPrintViewer1.Report = Report;
                }
                
            }
            catch { }
        }

        private void ReportFetchRecord()
        {
            try
            {
                if (classData == null) return;
                if (classData.payments.Count == 0 && false) return;
                var paymentModel = classData.payments.First();
                if (paymentModel == null)
                    paymentModel = new ClassPayment();
                PropertyInfo[] properties1 = paymentModel.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                Report.DetailGrid.Recordset.Empty();

                if (classData.payments.Count > 0)
                {
                    foreach (var payment in classData.payments)
                    {
                        Report.DetailGrid.Recordset.Append();

                        #region 商品明细与Grid++Report记录集的字段之间的对应关系
                        foreach (PropertyInfo item1 in properties1)
                        {
                            string name = item1.Name;
                            object value = item1.GetValue(payment, null);

                            foreach (IGRField fld in Report.DetailGrid.Recordset.Fields)
                            {
                                if (String.Compare(fld.RunningDBField, name, true) == 0)
                                {
                                    fld.Value = value;
                                    break;
                                }
                            }
                        }
                        #endregion

                        #region 与Grid++Report记录集的字段之间的对应关系
                        if (classData != null)
                        {
                            PropertyInfo[] properties2 = classData.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                            foreach (PropertyInfo item2 in properties2)
                            {
                                string name = item2.Name;
                                object value = item2.GetValue(classData, null);

                                foreach (IGRField fld in Report.DetailGrid.Recordset.Fields)
                                {
                                    if (String.Compare(fld.RunningDBField, name, true) == 0)
                                    {
                                        fld.Value = value;
                                        break;
                                    }
                                }
                            }
                        }
                        #endregion

                        Report.DetailGrid.Recordset.Post();
                    }
                }
                else
                {
                    Report.DetailGrid.Recordset.Append();

                    #region 与Grid++Report记录集的字段之间的对应关系
                    if (classData != null)
                    {
                        PropertyInfo[] properties2 = classData.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                        foreach (PropertyInfo item2 in properties2)
                        {
                            string name = item2.Name;
                            object value = item2.GetValue(classData, null);

                            foreach (IGRField fld in Report.DetailGrid.Recordset.Fields)
                            {
                                if (String.Compare(fld.RunningDBField, name, true) == 0)
                                {
                                    fld.Value = value;
                                    break;
                                }
                            }
                        }
                    }
                    #endregion

                    Report.DetailGrid.Recordset.Post();
                }

        
            }
            catch { }
        }

        //在C#中一次填入一条记录不能成功，只能使用一次将记录全部填充完的方式
        private void ReportFetchRecord_SubFoodDepart()
        {
            //获取子报表的内部报表对象  
            try
            {
                SubFoodDepart.DetailGrid.Recordset.Empty();
                if ((classData.departList == null) || (classData.departList.Count == 0)) return;
                var foodTypeInfo = classData.departList.First();
                PropertyInfo[] properties1 = foodTypeInfo.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (var foodType in classData.departList)
                {
                    SubFoodDepart.DetailGrid.Recordset.Append();

                    #region 分类明细与Grid++Report记录集的字段之间的对应关系
                    foreach (PropertyInfo item1 in properties1)
                    {
                        string name = item1.Name;
                        object value = item1.GetValue(foodType, null);

                        foreach (IGRField fld in SubFoodDepart.DetailGrid.Recordset.Fields)
                        {
                            if (String.Compare(fld.RunningDBField, name, true) == 0)
                            {
                                fld.Value = value;
                                break;
                            }
                        }
                    }
                    #endregion                    

                    SubFoodDepart.DetailGrid.Recordset.Post();
                }
            }
            catch
            { }
        }

        //在C#中一次填入一条记录不能成功，只能使用一次将记录全部填充完的方式
        private void ReportFetchRecord_SubFoodType()
        {
            //获取子报表的内部报表对象  
            try
            {
                SubFoodType.DetailGrid.Recordset.Empty();
                if ((classData.foodTypes == null) || (classData.foodTypes.Count == 0) || false) return;
                var foodTypeInfo = classData.foodTypes.First();
                PropertyInfo[] properties1 = foodTypeInfo.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (var foodType in classData.foodTypes)
                {
                    SubFoodType.DetailGrid.Recordset.Append();

                    #region 分类明细与Grid++Report记录集的字段之间的对应关系
                    foreach (PropertyInfo item1 in properties1)
                    {
                        string name = item1.Name;
                        object value = item1.GetValue(foodType, null);

                        foreach (IGRField fld in SubFoodType.DetailGrid.Recordset.Fields)
                        {
                            if (String.Compare(fld.RunningDBField, name, true) == 0)
                            {
                                fld.Value = value;
                                break;
                            }
                        }
                    }
                    #endregion                    

                    SubFoodType.DetailGrid.Recordset.Post();
                }
            }
            catch
            { }
        }

        private void uiButton1_Click(object sender, System.EventArgs e)
        {
            UIButton btn = (UIButton)sender;
            btn.Selected = true;
        }

        private void FOrders_Shown(object sender, System.EventArgs e)
        {
            LoadOrderDetail();
        }

        private void AddClassItem(int sItemType, string sField1, string sField2, string sField3 = "", string sField4 = "")
        {
            ClassItemInfo info = new ClassItemInfo();
            info.Field1 = sField1;
            info.Field2 = sField2;
            info.Field3 = sField3;
            info.Field4 = sField4;
            info.ItemType = sItemType;
            UIClassItem menu = new UIClassItem(info);
            menu.SetMinSize();
            layOrderDetail.Add(menu);
            StatusFormStepIt();
        }

        private void LoadOrderDetail()
        {
            layOrderDetail.Clear();
            layOrderDetail.Visible = false;
            try
            {
                classData = new corecmsfoodorderclassServices().GetClassData(AppConstVars.classId);
                if (classData == null)
                {
                    //AddClassItem(0, "******", "暂无数据", "******");
                    //return;
                    classData = new ClassDataDto();
                    classData.foodTypes = new List<ClassFoodType>();
                    classData.payments = new List<ClassPayment>();
                }

                AddClassItem(0, "交班单号：", classData.classNumber);
                AddClassItem(0, "首单时间：", classData.starDate.ToString("yyyy-MM-dd HH:mm:ss"));
                AddClassItem(0, "未单时间：", classData.endDate.ToString("yyyy-MM-dd HH:mm:ss"));
                AddClassItem(0, "班次：", classData.marketName, "收银员：", AppConstVars.sysUser.userName);
                layOrderDetail.Add(new UIMenuItemSeparator("", 10, 370));
                AddClassItem(1, "大类", "数量", "均价", "金额");
                layOrderDetail.Add(new UIMenuItemSeparator("", 10, 370));
                foreach (var item in classData.foodTypes)
                {
                    if (string.IsNullOrEmpty(item.typeName)) item.typeName = "不定";
                    AddClassItem(2, item.typeName, item.typeQuantity.ToString(), item.typePrice.ToString(), item.typeAmount.ToString());
                }
                layOrderDetail.Add(new UIMenuItemSeparator("", 10, 370));
                AddClassItem(0, "总单数：", classData.allCount.ToString(), "总人数：", classData.allPerson.ToString());
                AddClassItem(0, "单均价：", classData.avgBillPrice.ToString("0.0#"), "人均价：", classData.avgPersonPrice.ToString("0.0#"));
                AddClassItem(0, "总商品数：", classData.allFoodCount.ToString(), "退商品数：", classData.refundFoodCount.ToString());
                AddClassItem(0, "退菜数量：", CommFunc.ConvertToString(classData.refundQuantity), "退菜金额：", CommFunc.ConvertToString(classData.refundAmount));
                AddClassItem(0, "赠送数量：", CommFunc.ConvertToString(classData.presentCount), "赠送金额：", CommFunc.ConvertToString(classData.presentAmount));
                AddClassItem(0, "应收合计：", classData.sumShouldAmount.ToString(), "优惠金额：", classData.sunReduceAmount.ToString());
                AddClassItem(0, "实收合计：", classData.sumRealAmount.ToString(), "会员充值：", classData.sum_depAmount.ToString());
                AddClassItem(0, "营业合计：", classData.sumAllAmount.ToString(), "充值赠送：", classData.userGiftAmount.ToString());
                layOrderDetail.Add(new UIMenuItemSeparator("", 10, 370));
                AddClassItem(1, "付款方式", "消费金额", "会员充值", "合计");
                layOrderDetail.Add(new UIMenuItemSeparator("", 10, 370));

                foreach (var item in classData.payments)
                {
                    AddClassItem(2, item.payName.ToString(), item.posAmount.ToString(), item.depAmount.ToString(), item.allAmount.ToString());
                }
                layOrderDetail.Add(new UIMenuItemSeparator("", 10, 370));
                AddClassItem(2, "合计", CommFunc.ConvertToString(classData.sum_posAmount), CommFunc.ConvertToString(classData.sum_depAmount), CommFunc.ConvertToString(classData.sum_allAmount));
                layOrderDetail.Add(new UIMenuItemSeparator("", 10, 370));

                axGRPrintViewer1.Stop();
                Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
                //try
                //{
                //    SubFoodType = Report.ControlByName("SubFoodType").AsSubReport.Report;
                //    SubFoodType.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord_SubFoodType);
                //}
                //catch { }
                //try
                //{
                //    SubFoodDepart = Report.ControlByName("SubFoodDepart").AsSubReport.Report;
                //    SubFoodDepart.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord_SubFoodDepart);
                //}
                //catch { }                
                axGRPrintViewer1.Report = Report;
                axGRPrintViewer1.ZoomPercent = 200;
                axGRPrintViewer1.Start();

            }
            catch (Exception ex)
            {

            }
            finally
            {
                layOrderDetail.Visible = true;
                HideStatusForm();
            }
        }

        private void btnHomePage_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            new PrintServices().SetPrintClassBill(classData, false);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSettlementUn_Click(object sender, EventArgs e)
        {
            new PrintServices().SetPrintClassBill(classData, true);
        }

        private async void btnRefund_Click(object sender, EventArgs e)
        {
            var classServices = new corecmsfoodorderclassServices();
            var orderClass = classServices.GetById(AppConstVars.classId);
            if (orderClass == null)
            {
                UIMessageBox.Show("没有可交班的数据。", "出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }

            //if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isClassOff, 0)) return;
            if (!ShowAskDialog("确认要进行交班吗？")) return;
            cmd.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                var rs = await SendPostDuty(classData);
                if (!rs) return;
            }
            finally
            {
                cmd.HideOpaqueLayer();
            }

            orderClass.classOff = true;
            orderClass.endDate = DateTime.Now;
            var bl = classServices.Update(orderClass);
            if (bl) this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void FOrderList_Load(object sender, EventArgs e)
        {
            if (!AppConstVars.isAdminUser) btnSetup.Visible = false;
        }

        private void btnSetup_Click(object sender, EventArgs e)
        {
            new PrintServices().SetPrintClassDesign();
        }

        /// <summary>
        /// 发送订单
        /// 单次发送，不进行限制
        /// </summary>
        /// <param name="tableid"></param>
        public async Task<bool> SendPostDuty(ClassDataDto classInfo)
        {
            try
            {
                List<PosDutyRechargeModel> posDutyRecharge = new List<PosDutyRechargeModel>();
                List<PosDutySaleModel> posDutySale = new List<PosDutySaleModel>();

                var hbBusiness = new HandoverBusiness();

                //充值记录
                List<ApiPosDutyRecharge> rechargePayList = hbBusiness.GetDutyRechargeInfoList(classInfo);
                //消费记录
                List<ApiPosDutySale> salsePayList = hbBusiness.GetDutySalseInfoList(classInfo);

                DutyApiPostModel DutyApiInfo = new DutyApiPostModel();
                DutyApiInfo.tenantId = AppConstVars.sysStore.corpId.ToString();
                DutyApiInfo.deviceId = AppConstVars.sysStore.deviceId;
                DutyApiInfo.dutyCode = classData.classNumber;
                DutyApiInfo.dutyName = classData.classNumber;
                DutyApiInfo.posUserId = AppConstVars.sysUser.posUserId.ToString();
                DutyApiInfo.dutyDate = classData.starDate.ToShortDateString();
                DutyApiInfo.dutyBeginTime = classData.starDate.ToString();
                DutyApiInfo.dutyEndTime = classData.endDate.ToString();
                DutyApiInfo.username = AppConstVars.sysUser.userName;
                DutyApiInfo.boxAmount = classData.cashBoxMoney.Value;
                DutyApiInfo.openBoxAmount = classData.cashBoxMoney.Value;// DutyInfo.box_amount != null ? DutyInfo.box_amount.ToDecimal() : 0;
                DutyApiInfo.createBy = AppConstVars.sysUser.userName.ToString();
                DutyApiInfo.createTime = classData.starDate.ToString();
                DutyApiInfo.branchId = AppConstVars.sysStore.branchId.ToString();
                DutyApiInfo.status = "1";

                DutyApiInfo.posDutyRechargeList = rechargePayList;
                DutyApiInfo.posDutySaleList = salsePayList;

                AdminUiCallBack rs = await SystemApiUtil.SendPostDuty(DutyApiInfo);

                if (rs.code != 200)
                {
                    UIMessageBox.Show($"推送交班订单失败:{rs.msg}");
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                UIMessageBox.Show($"推送交班订单失败:{ex.Message}");
                return false;
            }
        }

        private void btnPrintAndOff_Click(object sender, EventArgs e)
        {
            btnPrint_Click(sender, e);
            btnRefund_Click(sender, e);
        }
    }
}
